//
//  HttpBaseTool.m
//  Pods
//
//  Created by iOS on 2017/3/24.
//
//

#import "HttpBaseTool.h"

@implementation HttpBaseTool

+ (AFHTTPSessionManager *)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    // 网络加载动画视图
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
    // 设置文字
    hud.labelText = @"正在加载";
    hud.labelColor = kGrayTextColor;
    // 设置图片
    hud.customView = [HMHUDManager loadingAnimationViewWithFrame:CGRectMake(0, 0, 40, 40)];
    // 设置透明度
    hud.opacity = 0;
    // 再设置模式
    hud.mode = MBProgressHUDModeCustomView;
    // 隐藏时候从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    
    MyLog(@"GETURL:%@,%@",url,params);
    // 1.获得请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer.timeoutInterval =10.0f;
    //https
    AFSecurityPolicy *securityPolicy =[AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates =YES;
    mgr.securityPolicy =securityPolicy;
    
    AFHTTPResponseSerializer *serializer = [AFHTTPResponseSerializer serializer];
    serializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"baiduapp/json",@"text/html",@"text/plain",nil];
    mgr.responseSerializer = serializer;
    // 2.发送GET请求
    [mgr GET:[kBaseUrl stringByAppendingString:url] parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
       
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hide:YES];

        if (success) {
            NSDictionary *responseDic =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            MyLog(@"GETResponse:%@",responseDic);
            success(responseDic);
            [UIApplication sharedApplication].networkActivityIndicatorVisible =NO;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hide:YES];

        if (failure) {
            failure(error);
            [UIApplication sharedApplication].networkActivityIndicatorVisible =NO;
        }
    }];
    return mgr;
}
+ (AFHTTPSessionManager *)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
//     网络加载动画视图
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
    // 设置文字
    hud.labelText = @"正在加载";
    hud.labelColor = kGrayTextColor;
    // 设置图片
    hud.customView = [HMHUDManager loadingAnimationViewWithFrame:CGRectMake(0, 0, 40, 40)];
    // 设置透明度
    hud.opacity = 0;
    // 再设置模式
    hud.mode = MBProgressHUDModeCustomView;
    // 隐藏时候从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    
    MyLog(@"POSTURL:%@,%@",url,params);
    // 1.获得请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer.timeoutInterval =10.0f;
    //https
    AFSecurityPolicy *securityPolicy =[AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates =YES;
    mgr.securityPolicy =securityPolicy;
    
    AFHTTPResponseSerializer *serializer = [AFHTTPResponseSerializer serializer];
    serializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"baiduapp/json",@"text/html",@"text/plain",nil];
    mgr.responseSerializer = serializer;
    // 2.发送POST请求
    [mgr POST:[kBaseUrl stringByAppendingString:url] parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hide:YES];
  
        if (success) {
            NSDictionary *responseDic =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            MyLog(@"POSTResponse:%@",responseDic);
            success(responseDic);
            [UIApplication sharedApplication].networkActivityIndicatorVisible =NO;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hide:YES];
       
        if (failure) {
            failure(error);
            [UIApplication sharedApplication].networkActivityIndicatorVisible =NO;
        }
    }];
    return mgr;
}

+ (AFHTTPSessionManager *)post:(NSString *)url params:(NSDictionary *)params images:(NSArray *)images imagesName:(NSArray*)imagesName success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeDeterminate;
    
    MyLog(@"POSTIMAGEURL:%@,%@",url,params);
    [UIApplication sharedApplication].networkActivityIndicatorVisible =YES;
    if (images.count ==0 ||!images) {
        [HttpBaseTool post:url params:params success:success failure:failure];
        [hud hide:YES];
        return nil;
    }
    // 1.获得请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer.timeoutInterval =30.0f;
    //https
    AFSecurityPolicy *securityPolicy =[AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates =YES;
    mgr.securityPolicy =securityPolicy;
    
    AFHTTPResponseSerializer *serializer = [AFHTTPResponseSerializer serializer];
    serializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"baiduapp/json",@"text/html",@"text/plain",nil];
    mgr.responseSerializer = serializer;
    
    // 2.发送POST请求
    [mgr POST:[kBaseUrl stringByAppendingString:url] parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (images) {
            for (int i=0; i<images.count; i++) {
                UIImage *image =images[i];
                
                if (images.count ==1) {
                    NSData *data =UIImageJPEGRepresentation(image, 0.1);
                    [formData appendPartWithFileData:data name:@"photo" fileName:imagesName[i] mimeType:@"image/jpeg"];
                }else{
                    NSData *data =UIImageJPEGRepresentation(image, 0.1);
                    [formData appendPartWithFileData:data name:@"photo[]" fileName:imagesName[i] mimeType:@"image/jpeg"];
                }
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"uploadProgress.completedUnitCount = %lld, uploadProgress.totalUnitCount = %lld", uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
        float progres = (float)uploadProgress.completedUnitCount / (float)uploadProgress.totalUnitCount;
        NSLog(@"progres = %.2f", progres);
        hud.progress = progres;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hide:YES];
        if (success) {
            NSDictionary *responseDic =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            MyLog(@"POSTIMAGEResponse:%@",responseDic);
            success(responseDic);
            [UIApplication sharedApplication].networkActivityIndicatorVisible =NO;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hide:YES];
        if (failure) {
            failure(error);
            [UIApplication sharedApplication].networkActivityIndicatorVisible =NO;
        }
    }];
    return mgr;
}

+ (AFHTTPSessionManager *)post:(NSString *)url params:(NSDictionary *)params imageParm:(NSString *)imagrParm images:(NSArray *)images imagesName:(NSArray*)imagesName success:(void (^)(id))success failure:(void (^)(NSError *))failure {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeDeterminate;
    
    MyLog(@"POSTIMAGEURL:%@,%@",url,params);
    [UIApplication sharedApplication].networkActivityIndicatorVisible =YES;
    if (images.count ==0 ||!images) {
        [HttpBaseTool post:url params:params success:success failure:failure];
        [hud hide:YES];
        return nil;
    }
    // 1.获得请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer.timeoutInterval =30.0f;
    //https
    AFSecurityPolicy *securityPolicy =[AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates =YES;
    mgr.securityPolicy =securityPolicy;
    
    AFHTTPResponseSerializer *serializer = [AFHTTPResponseSerializer serializer];
    serializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"baiduapp/json",@"text/html",@"text/plain",nil];
    mgr.responseSerializer = serializer;
    
    // 2.发送POST请求
    [mgr POST:[kBaseUrl stringByAppendingString:url] parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (images) {
            for (int i=0; i<images.count; i++) {
                UIImage *image =images[i];
                NSData *data =UIImageJPEGRepresentation(image, 0.1);
                [formData appendPartWithFileData:data name:imagrParm fileName:imagesName[i] mimeType:@"image/jpeg"];
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"uploadProgress.completedUnitCount = %lld, uploadProgress.totalUnitCount = %lld", uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
        float progres = (float)uploadProgress.completedUnitCount / (float)uploadProgress.totalUnitCount;
        NSLog(@"progres = %.2f", progres);
        hud.progress = progres;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hide:YES];
        if (success) {
            NSDictionary *responseDic =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            MyLog(@"POSTIMAGEResponse:%@",responseDic);
            success(responseDic);
            [UIApplication sharedApplication].networkActivityIndicatorVisible =NO;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hide:YES];
        if (failure) {
            failure(error);
            [UIApplication sharedApplication].networkActivityIndicatorVisible =NO;
        }
    }];
    return mgr;
}

+ (void)requestWithBaseUrl:(NSString *)baserUrl path:(NSString *)path method:(request_type)method isJSON:(BOOL)isJson params:(id)parm ssuccess:(void (^)(id responseObj))success failure:(void (^)(NSError *error))failure {
    if (method == POST_REQUEST) {
        [self post:path params:parm success:^(id responseObj) {
            success(responseObj);
        } failure:^(NSError *error) {
            failure(error);
        }];
    }
    if (method == GET_REQUEST) {
        [self get:path params:parm success:^(id responseObj) {
            success(responseObj);
        } failure:^(NSError *error) {
            failure(error);
        }];
    }
}

@end
